import { ReviewRolesService } from 'src/app/@core/services/ReviewRoles/review-roles.service';
import { Component, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { DValidateRules, DialogService, FormLayout, TableWidthConfig } from 'ng-devui';
import { SaleReturn } from 'src/app/@core/data/sale';
import { CustomerService } from 'src/app/@core/services/customer/customer.service';
import { DataSharingService } from 'src/app/@core/services/dataSharing/data-sharing.service';
import { EncodeRulesService } from 'src/app/@core/services/encoderRule/encode-rules.service';
import { MaterialService } from 'src/app/@core/services/material/material.service';
import { SalesService } from 'src/app/@core/services/sales/sales.service';
import { UserService } from 'src/app/@core/services/user/user.service';
import { SelectCustomerComponent } from 'src/app/@shared/components/select-customer/select-customer.component';
import { SelectMaterialComponent } from 'src/app/@shared/components/select-material/select-material.component';
import { SelectUserComponent } from 'src/app/@shared/components/select-user/select-user.component';
import * as XLSX from 'xlsx';
import { SetDeliveryDateComponent } from '../../sales-order/set-delivery-date/set-delivery-date.component';
import { SelectSalesOrderComponent } from '../../sales-order/add-sales-order/select-sales-order/select-sales-order.component';
import { SelectInventoryComponent } from 'src/app/@shared/components/select-inventory/select-inventory.component';
import { environment } from 'src/environments/environment';
import { SelectSalesInvoiceComponent } from '../sales-return-add/select-sales-invoice/select-sales-invoice.component';

@Component({
  selector: 'app-sales-return-edit',
  templateUrl: './sales-return-edit.component.html',
  styleUrls: ['./sales-return-edit.component.scss']
})
export class SalesReturnEditComponent {
  Math = Math;
  layoutDirection: FormLayout = FormLayout.Horizontal;
  SaleReturn:SaleReturn ={
    orderDate:null,
    saleReturnNum: '',
    saleReturnCustomerId: 0,
    company: '',
    customerContactName: '',
    chineseName: '',
    customerAbbreviation: '',
    customerContactPhone: '',
    saleReturnSalesmanId: 0,
    salesmanName: '',
    saleReturnDepartmentId: 0,
    departmentName: '',
    scheduledReturnTime:null,
    returnType: '',
    currencyName: '',
    settlementMethodName: '',
    isWriteOff: false,
    note: '',
    status: '未开始审核',
    isReturn: false,
    isReceive: false,
    isCancellation: false,
    isPrint: false,
    createTime: '',
    createUser: '',
    returnedAmount: 0,
    unReturnedAmount: 0,
    returnAmount: 0,
    taxAmount: 0,
    tax: 0,
    unTaxAmount: 0,
    taxDiscountAmount: 0,
    taxDiscount: 0,
    discountAmount: 0,
    file: [],
    fileNote: [],
    saleReturnParts: [
      {
        saleReturnPartPartId: 0,
        partNum: '',
        partName: '',
        scheduledReturnTime: null,
        scheduledReturnAmount: 0,
        returnedAmount: 0,
        returningAmount: 0,
        saleReturnPartWarehouseId: 0,
        warehouseName: '',
        saleReturnPartPositionId: 0,
        positionName: '',
        priceWithTax: 0,
        priceWithoutTax: 0,
        taxRate: 0,
        discount: 0,
        discountPriceWithTax: 0,
        amountWithTax: 0,
        amountWithoutTax: 0,
        taxAmount: 0,
        discountAmountWithTax: 0,
        discountAmountWithoutTax: 0,
        discountTaxAmount: 0,
        note: '',
        saleOrderNum: '',
        saleDeliverNum: '',
        saleDeliverPartId: 0,
        partType: '',
        partUOM: '',
        image: '',
        description: ''
      }
    ]
  }

  tableWidthConfig: TableWidthConfig[] = [
    {
      field: '操作',
      width: '150px'
    },
    {
      field: '物料编码',
      width: '200px'
    },
    {
      field: '图片',
      width: '150px'
    },
    {
      field: '物料名称',
      width: '150px'
    },
    {
      field: '规格型号',
      width: '150px'
    },
    {
      field: '物料描述',
      width: '150px'
    },
    {
      field: '计划发货日期',
      width: '200px'
    },
    {
      field: '实时库存',
      width: '150px'
    },
    {
      field: '数量',
      width: '170px'
    },
    {
      field: '已退数量',
      width: '150px'
    },
    {
      field: '可退数量',
      width: '150px'
    },
    {
      field: '数量',
      width: '170px'
    },
    {
      field: '退货仓库',
      width: '170px'
    },
    {
      field: '退货库位',
      width: '170px'
    },
    {
      field: '单位',
      width: '150px'
    },
    {
      field: '单价(含税)',
      width: '170px'
    },
    {
      field: '单价（不含税）',
      width: '150px'
    },
    {
      field: '税率（%）',
      width: '170px'
    },
    {
      field: '折扣（%）',
      width: '150px'
    },
    {
      field: '折扣单价（含税）',
      width: '150px'
    },
    {
      field: '含税金额',
      width: '150px'
    },
    {
      field: '不含税金额',
      width: '150px'
    },
    {
      field: '税额',
      width: '150px'
    },
    {
      field: '折扣不含税金额',
      width: '150px'
    },
    {
      field: '折扣含税金额',
      width: '150px'
    },
    {
      field: '折扣税额',
      width: '150px'
    },

    {
      field: '来源报价单号',
      width: '150px'
    }
  ];
  dataTableOptions = {
    columns: [
      {
        field: 'name',
        header: '物料编码',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '图片',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '物料名称',
        fieldType: 'text',
      },

      {
        field: 'name',
        header: '规格型号',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '物料描述',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '退货日期',
        fieldType: 'text',
      },

      {
        field: 'name',
        header: '已退数量',
        fieldType: 'text',
      },

      {
        field: 'name',
        header: '退货数量',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '退货仓库',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '退货仓位',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '单位',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '单价(含税)',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '单价（不含税）',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '税率（%）',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '折扣（%）',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '折扣单价（含税）',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '含税金额',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '不含税金额',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '税额',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '折扣不含税金额',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '折扣含税金额',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '折扣税额',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '备注',
        fieldType: 'text',
      },

      {
        field: 'name',
        header: '来源报价单号',
        fieldType: 'text',
      },
    ]
  };
  saleOrderRules: { [key: string]: DValidateRules } = {
    saleOrderNum: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*订单号不能为空' },
        { minlength: 2, message: '*订单号长度至少为2' },
        { maxlength: 40, message: '*订单号长度至多为40' },
        { pattern: /^[^\s]*$/, message: '*订单号不能包含空格' }
      ]
    },
    customerName: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*客户不能为空' },
      ]
    },
    orderDate: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*单据日期不能为空' },
      ]
    },
    partNum: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*物料不能为空' },
      ]
    },
    plannedShipmentDate: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*计划发货时间不能为空' },
      ]
    },
    deliveryDate: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*计划交货时间不能为空' },
      ]
    },
    priceWithTax: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*物料单价不能为空' },
      ]
    },
    quantity: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*数量不能为空' },
      ]
    },
    salesman: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*数量不能为空' },
      ]
    }
  }
  customerLinkMan: any = [];
  msgs: Array<Object> = [];
  customerContact: any = [];
  currencyOptions: any = [];
  settlementMethodOptions: any = [];
  data: any;
  loadData: boolean;
  collectionPeriods: any;
  id:any
  constructor(private DialogService: DialogService, private UserService: UserService, private CustomerService: CustomerService, private SalesService: SalesService, private MaterialService: MaterialService, private router: Router, private EncodeRulesService: EncodeRulesService, private dataSharingService: DataSharingService, private activatedRoute: ActivatedRoute,private ReviewRolesService:ReviewRolesService) { }
  ngOnInit(): void {
  ;
    this.activatedRoute.params.subscribe((params:any)=>{
      if(params.id){
        this.id = params.id
        this.SalesService.GetSaleReturnById(params.id).subscribe((data:any)=>{
          this.SaleReturn = data
          this.SaleReturn.orderDate = new Date(data.orderDate)
          this.SaleReturn.scheduledReturnTime = new Date(data.scheduledReturnTime)
          this.SaleReturn.saleReturnParts.forEach(part => {
            part.scheduledReturnTime = new Date(part.scheduledReturnTime)
          })
          this.calculateTotal()
        }
        )}
    })
    this.CustomerService.GetPagedCurrency(1, 9999).subscribe((data: any) => {
      this.currencyOptions = data.items;
    })
    this.CustomerService.GetPagedSettlementMethod(1, 9999).subscribe((data: any) => {
      this.settlementMethodOptions = data.items;
    })
    this.CustomerService.GetPagedCollectionPeriod({})
    const userinfoString = localStorage.getItem('userinfo');
    if (userinfoString) {
      this.SaleReturn.createUser = JSON.parse(userinfoString).username;
    }
    this.CustomerService.GetPagedCollectionPeriod({
      PageSize: 999,
      PageNumber: 1,
      SearchStatus: '收款'
    }).subscribe((data: any) => {
      this.collectionPeriods = data.items
    })
  }
  addRowA(index:number,rowItem:any){
    const newRowItem = {...rowItem};
    this.SaleReturn.saleReturnParts.splice(index+1,0,newRowItem);
    this.SaleReturn.saleReturnParts[index+1].scheduledReturnAmount = 0;
  }
  addRow() {
    this.SaleReturn.saleReturnParts.push({
      saleReturnPartPartId: 0,
      partNum: '',
      partName: '',
      scheduledReturnTime: null,
      scheduledReturnAmount: 0,
      returnedAmount: 0,
      returningAmount: 0,
      saleReturnPartWarehouseId: 0,
      warehouseName: '',
      saleReturnPartPositionId: 0,
      positionName: '',
      priceWithTax: 0,
      priceWithoutTax: 0,
      taxRate: 0,
      discount: 0,
      discountPriceWithTax: 0,
      amountWithTax: 0,
      amountWithoutTax: 0,
      taxAmount: 0,
      discountAmountWithTax: 0,
      discountAmountWithoutTax: 0,
      discountTaxAmount: 0,
      note: '',
      saleOrderNum: '',
      saleDeliverNum: '',
      saleDeliverPartId: 0,
      partType: '',
      partUOM: '',
      image: '',
      description: ''
    })
  }//添加行
  deleteRow(index: number) {
    this.SaleReturn.saleReturnParts.splice(index, 1);
    this.calculateTotal()
    if (this.SaleReturn.saleReturnParts.length == 0) {
      this.addRow();
    }
  }//删除行
  taxRateChange(rowitem: any, value: number) {
    rowitem.taxRate = value / 100;
    this.calculateAmount(rowitem);
    this.calculateTotal();
  }//税率改变
  quantityChange(rowitem: any) {
    this.calculateAmount(rowitem)
    this.calculateTotal()
  }//数量改变
  priceWithTaxChange(rowitem: any) {
    this.calculateAmount(rowitem)
    this.calculateTotal()
  }//含税单价改变
  discountChange(rowitem: any, value: number) {
    rowitem.discount = value / 100;
    this.calculateAmount(rowitem)
    this.calculateTotal()
  }//折扣改变
  calculateAmount(item: any): void {
    //计算不含税单价，并保留6位小数
    item.priceWithoutTax = +(item.priceWithTax / (1 + item.taxRate)).toFixed(4);
    // 计算不含税金额，并保留6位小数
    item.amountWithoutTax = +(item.scheduledReturnAmount * item.priceWithoutTax).toFixed(4);
    // 计算税额，并保留6位小数
    item.taxAmount = +(item.amountWithoutTax * item.taxRate).toFixed(4);
    // 计算含税金额，并保留6位小数
    item.amountWithTax = +(item.priceWithTax * item.scheduledReturnAmount).toFixed(4);
    // 计算折扣后含税单价，并保留6位小数
    item.discountedPriceWithTax = +(item.priceWithTax * item.discount).toFixed(4);
    // 计算折扣后不含税金额，并保留6位小数
    item.discountAmountWithoutTax = +(item.amountWithoutTax * item.discount).toFixed(4);
    // 计算折扣后税额，并保留6位小数
    item.discountTaxAmount = +(item.discountAmountWithoutTax * item.taxRate).toFixed(4);
    // 计算折扣后含税金额，并保留6位小数
    item.discountAmountWithTax = +(item.discountAmountWithoutTax + item.discountTaxAmount).toFixed(4);
  }
  calculateTotal() {
    this.SaleReturn.returnAmount = this.SaleReturn.saleReturnParts.reduce((prev, cur) => prev + cur.scheduledReturnAmount, 0);
    this.SaleReturn.taxAmount = this.SaleReturn.saleReturnParts.reduce((prev, cur) => prev + cur.amountWithTax, 0);
    this.SaleReturn.tax = this.SaleReturn.saleReturnParts.reduce((prev, cur) => prev + cur.taxAmount, 0);
    this.SaleReturn.taxDiscountAmount = this.SaleReturn.saleReturnParts.reduce((prev, cur) => prev + cur.discountAmountWithTax, 0);
    this.SaleReturn.discountAmount = this.SaleReturn.saleReturnParts.reduce((prev, cur) => prev + cur.discountTaxAmount, 0);
    this.SaleReturn.taxDiscount = this.SaleReturn.saleReturnParts.reduce((prev,cur)=> prev + cur.discountTaxAmount,0)
  }//计算总金额
  isStartApproval: boolean = false
  isStartApprovalChange() {
    this.isStartApproval = true
  }
  submit($event: any) {
    if ($event.valid) {
      this.SaleReturn.createTime = new Date()
      this.SalesService.UpdateSaleReturn(this.id,this.SaleReturn).subscribe((data: any) => {
        if(this.isStartApproval){
          this.ReviewRolesService.StartApprovalFlow('销售退货单审核流配置',[this.SaleReturn.saleReturnNum]).subscribe((data:any)=>{
            this.showToast('success', '成功', '提交成功')
            setTimeout(() => {
              this.router.navigate(['/pages/sales-master/sales-return-order'])
            }, 1000);
          },
          (error: any) => {
            this.showToast('danger', '错误', '表单更新成功，审核流启动失败')
            setTimeout(() => {
              this.router.navigate(['/pages/sales-master/sales-return-order'])
            }, 1000);
          }
        )
        }else{
          this.showToast('success', '成功', '更新成功')
          setTimeout(() => {
            this.router.navigate(['/pages/sales-master/sales-return-order'])
          }, 1000);
        }
      },(error: any) => {
        if (error.status === 404) {
          this.showToast('error', '错误', '网络连接错误');
        } else {
          this.showToast('error', '错误', error.error);
        }
      }
      )
    }
    else {
      this.showToast('warn', '错误', '请填写必填项')
    }
  }//提交
  selectMaterial(rowItem: any, dialogtype?: string) {
    const results = this.DialogService.open({
      id: 'Add',
      maxHeight: '400px',
      width: '800px',
      backdropCloseable: true,
      data: "",
      title: '选择物料',
      content: SelectMaterialComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            rowItem.partNum = results.modalContentInstance.selectData.partNum;
            rowItem.image = results.modalContentInstance.selectData.fileURL;
            rowItem.partName = results.modalContentInstance.selectData.partName;
            rowItem.partType = results.modalContentInstance.selectData.partType;
            rowItem.description = results.modalContentInstance.selectData.description;
            rowItem.partUOM = results.modalContentInstance.selectData.partUOM;
            rowItem.priceWithTax = results.modalContentInstance.selectData.salePrice;
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  getImagesArray(fileURL: string): string[] {
    let urls = fileURL.split(',');
    urls = urls.map(url => environment.modifiedApiUrl + url);
    return urls;
  }
  showToast(type: any, summary: any, content: any) {
    switch (type) {
      default:
        this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  }//提示框
  @ViewChild('fileInput') fileInput: any;
  onButtonClick() {
    // 当按钮被点击时，触发文件输入的点击事件
    this.fileInput.nativeElement.click();
  }
  setDeliveryDate(dialogtype?: string) {
    let data = {
      display: false
    };
    const results = this.DialogService.open({
      id: 'Add',
      maxHeight: '400px',
      width: '400px',
      backdropCloseable: true,
      data: data,
      title: '选择退货日期',
      content: SetDeliveryDateComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if (results.modalContentInstance.form.plannedShipmentDate) {
              this.SaleReturn.saleReturnParts.forEach((item) => {
                item.scheduledReturnTime = results.modalContentInstance.form.plannedShipmentDate;
                results.modalInstance.hide();

              })
            } else {
              data.display = true;
            }
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  cancel() {
    this.router.navigate(['/pages/sales-master/sales-return-order'])
  }
  SelectStorehouse(rowItem:any,dialogtype?:string){
    if(rowItem.partNum==""){
      this.showToast('error', '错误', '请先选择物料')
      return
    }
    const results = this.DialogService.open({
      id: 'dialog-service',
      showAnimation: true,
      width:'1000px',
      title: '选择仓库',
      data:rowItem,
      content: SelectInventoryComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'primary',
          text: '确定',
          disabled: false,
          handler: ($event: Event) => {
            if(results.modalContentInstance.selectData){

               rowItem.saleReturnPartWarehouseId=results.modalContentInstance.selectData.warehouseId;
                rowItem.warehouseName =results.modalContentInstance.selectData.warehouseName;
                rowItem.saleReturnPartPositionId = results.modalContentInstance.selectData.positionId;
                rowItem.positionName =results.modalContentInstance.selectData.positionName;
                rowItem.realTimeInventory = results.modalContentInstance.selectData.partPositionInventory;
              }
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  selectOrder(dialogtype?: string) {
    const saleDeliverPartIds = this.SaleReturn.saleReturnParts.map(
      (item:any)=>{
        return item.saleDeliverPartId
      }
    )
    const results = this.DialogService.open({
      id: 'Add',
      width: '1250px',
      backdropCloseable: true,
      title: '选择销售发货单',
      data:saleDeliverPartIds,
      content: SelectSalesInvoiceComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if (results.modalContentInstance.filterRows) {
              if(this.checkCustomerIDs(results.modalContentInstance.filterRows)){
                if (results.modalContentInstance.filterRows.length > 1) {
                  this.CustomerService.GetCustomerById(results.modalContentInstance.filterRows[0].saleDeliverCustomerId).subscribe((data: any) => {
                    this.SaleReturn.saleReturnCustomerId = data.customerId
                    this.customerLinkMan = data.customerContacts
                    this.SaleReturn.chineseName = data.chineseName
                    this.SaleReturn.customerAbbreviation = data.customerAbbreviation
                    this.SaleReturn.currencyName = data.customerCurrencyName
                    this.SaleReturn.settlementMethodName = data.customerSettlementMethodName
                    this.SaleReturn.customerContactName = data.customerContacts[0].customerContactName
                    this.SaleReturn.customerContactPhone = data.customerContacts[0].phone
                    this.customerContact = { customerContactId: data.customerContacts[0].customerContactId, customerContactName: data.customerContacts[0].customerContactName }
                    this.UserService.GetUserById(data.salesmanId).subscribe((data: any) => {
                      this.SaleReturn.salesmanName = data.name
                      this.SaleReturn.saleReturnSalesmanId = data.id
                      this.SaleReturn.saleReturnDepartmentId = data.departmentId
                      this.UserService.GetDepartmentById(data.departmentId).subscribe((data: any) => {
                        this.SaleReturn.departmentName = data.name
                      })
                    })
                  })
                }else{
                  this.CustomerService.GetCustomerById(results.modalContentInstance.filterRows[0].saleDeliverCustomerId).subscribe((data: any) => {
                    this.SaleReturn.saleReturnCustomerId = data.customerId
                    this.SaleReturn.chineseName = data.chineseName
                    this.customerLinkMan = data.customerContacts
                    this.SaleReturn.customerContactName = data.customerAbbreviation
                  })
                  this.SalesService.GetSaleDeliverById(results.modalContentInstance.filterRows[0].saleDeliverPartSaleDeliverId).subscribe((data: any) => {
                    this.SaleReturn.salesmanName = data.salesmanName
                    this.SaleReturn.customerAbbreviation = data.customerAbbreviation
                    this.SaleReturn.currencyName = data.currencyName
                    this.SaleReturn.settlementMethodName = data.settlementMethodName
                    this.SaleReturn.customerContactName = data.customerContactName
                    this.SaleReturn.customerContactPhone = data.customerContactPhone
                    this.SaleReturn.departmentName = data.departmentName
                    this.SaleReturn.note = data.note
                  })
                }
                this.SaleReturn.saleReturnParts = this.SaleReturn.saleReturnParts.filter(part => part.partNum!==""&&part.partNum!==null)
                const saleOrderParts  = results.modalContentInstance.filterRows.map((item: any) => ({
                  partNum: item.partNum,
                  image: item.fileURL,
                  partName: item.partName,
                  partType: item.partType,
                  description: item.description,
                  partUOM: item.partUOM,
                  priceWithTax: item.priceWithTax,
                  priceWithoutTax: 0,
                  scheduledDeliverAmount: item.scheduledDeliverAmount,
                  realTimeInventory: 0,
                  scheduledReturnAmount: item.scheduledDeliverAmount-item.returnedAmount,
                  taxRate: item.taxRate,
                  discount: item.discount,
                  discountPriceWithTax: 0,
                  amountWithTax: 0,
                  amountWithoutTax: 0,
                  taxAmount: 0,
                  returnedAmount: item.returnedAmount,
                  discountAmountWithTax: 0,
                  discountAmountWithoutTax: 0,
                  discountTaxAmount: 0,
                  partRemark: item.note,
                  saleOrderNum: item.saleOrderNum,
                  saleDeliverPartWarehouseName: item.warehouseName,
                  saleDeliverPartPositionName: item.positionName,
                  saleReturnPartWarehouseId: item.saleDeliverPartWarehouseId,
                  saleReturnPartPositionId: item.saleDeliverPartPositionId,
                  saleDeliverNum: item.saleDeliverNum,
                  saleOrderId: item.saleDeliverPartSaleDeliverId,
                  partId: item.saleDeliverPartPartId,
                  saleDeliverPartId:item.saleDeliverPartId
                }));
                this.SaleReturn.saleReturnParts = this.SaleReturn.saleReturnParts.concat(saleOrderParts);
                this.SaleReturn.saleReturnParts.forEach(part => this.calculateAmount(part));
                this.calculateTotal();
                results.modalInstance.hide();
              }else{
                this.showToast('error', '错误', '请选择同一客户的销售发货单')
              }
            }
            results.modalInstance.hide();
          }
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ]
    })
  }
  checkCustomerIDs(customerRows:any) {
    // 如果数组长度为1或为空，直接返回true
    if (customerRows.length <= 1) {
      return true;
    }
    // 获取第一个元素的customerID
    const firstCustomerID = customerRows[0].saleDeliverCustomerId;
    // 检查数组中每个元素的customerID是否都与第一个元素的customerID相同
    return customerRows.every((row: any) => row.saleDeliverCustomerId === firstCustomerID);
  }
}
